﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.ServiceModel;
using System.IO;
using System.Threading;

namespace SURLService
{
    class SURLJob: IJob
    {
        private HttpListenerContext _context;
        private SURLDictionary _dict;
        private SURLServer _server;

        public static long counter = 0;
        
        public SURLJob(HttpListenerContext context, SURLDictionary dict, SURLServer server)
        {
            _context = context;
            _dict = dict;
            _server = server;
        }

        public void Run()
        {
            Interlocked.Increment(ref counter);
            Console.WriteLine("Got {0} jobs", counter);

            HttpListenerRequest request = _context.Request;
            HttpListenerResponse response = _context.Response;
            
            if (request.HttpMethod == "GET")
            {
                string RawUrl = request.RawUrl;
                if (RawUrl.StartsWith("/u/"))
                {
                    // query a short url
                    string sid = RawUrl.Substring(3);
                    int id = -1;
                    if (Int32.TryParse(sid, out id))
                    {
                        string url = _dict.Get(id);
                        if (url != null)
                        {
                            Console.WriteLine("Redirect to {0}", url);
                            response.Redirect(url);
                            response.Close();
                            return;
                        }
                    }
                }
                else if (RawUrl.StartsWith("/n?u="))
                {
                    // create new entry   
                    string url = RawUrl.Substring(5);

                    bool ret = _server.Propose(new NewURLCommand() { URL = url });
                    
                    if (ret)
                    {
                        Console.WriteLine("Add {0} up to Server", url);
                    }
                    else
                    {
                        Console.WriteLine("Failed to add {0} up to Server", url);
                    }
                    
                    StreamWriter writer = new StreamWriter(response.OutputStream);
                    writer.WriteLine(ret);
                    writer.Close();
                    response.Close();
                    return;
                }

                response.StatusCode = 404;
                response.Close();
            }
        }
    }
}
